#include "buildFilm.h"
#include "buildFilter.h"

#include "katanafilm.h"
#include "film/image.h"

#include <Render/RenderSettings.h>
#include <RendererInfo/RenderMethod.h>


Film *getFilm( FnKat::Render::RenderSettings &renderSettings,
               const string &outputName,
               BasicSettings* basicSettings )
{
    FnKat::Render::RenderSettings::RenderOutputs outputs = renderSettings.getRenderOutputs();

    if (outputs.size() == 0)
    {
        std::cerr << "No Outputs defined!" << std::endl;
        return NULL;
    }

    FnKat::Render::RenderSettings::RenderOutput output = outputs.begin()->second;
    if (output.type != "color")
    {
        std::cerr << "Invalid output Type!" << std::endl;
        return NULL;
    }

    // Get the filter
    Filter *filter = getFilter(renderSettings);

    // Resolution
    int dataWindow[4];
    renderSettings.getDataWindow(dataWindow);
    int xres = dataWindow[2] - dataWindow[0];
    int yres = dataWindow[3] - dataWindow[1];

    // Common params
    ParamSet p;
    p.AddInt("xresolution", &xres, 1);
    p.AddInt("yresolution", &yres, 1);

    std::string renderMethodName = basicSettings->renderMethodName;
    if( renderMethodName == FnKat::RendererInfo::PreviewRenderMethod::kDefaultName )
    {
        // Host Address
        std::string hostAddress = basicSettings->hostAddress;
        float frameTime = basicSettings->frameTime;

        // Crop
        float crop[4];
        renderSettings.getCropWindow(crop);

        // Get output channels
        FnKat::Render::RenderSettings::ChannelBuffers channelBuffers;
        renderSettings.getChannelBuffers( channelBuffers );

        FnKat::Render::RenderSettings::ChannelBuffers::const_iterator it;
        it = channelBuffers.begin();

        std::string frameName = it->first;
        FnKat::Render::RenderSettings::ChannelBuffer buffer = it->second;
        int frameId = atoi( buffer.bufferId.c_str() );

        p.AddString("outputAddress", &hostAddress, 1);
        p.AddFloat("frameTime", &frameTime, 1);

        p.AddFloat("cropWindow", crop, 4);
        p.AddInt("frameId", &frameId, 1);

        return CreateKatanaFilm( p, filter);
    }
    else if ( renderMethodName == FnKat::RendererInfo::DiskRenderMethod::kDefaultName )
    {
        std::string filename = output.renderLocation;
        p.AddString("filename", &filename, 1);

        return CreateImageFilm(p, filter);
    }
    else
    {
        std::cerr << "Invalid Render Method" << std::endl;
        return NULL;
    }

}
